import { ManageRole } from './../../interface/interface';
import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { NzTreeNode, NzTreeComponent, NzFormatEmitEvent, NzTreeNodeOptions } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserManagementService } from '../../user-management.service';
import { RoleTree } from '../../roles.data';
import { createTreeData } from './test';
import { ToolsService } from 'app/shared/service';
import { NzMessageService } from 'ng-zorro-antd';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-add-role',
    templateUrl: './add-role.component.html',
    styleUrls: ['./add-role.component.css']
})
export class AddRoleComponent implements OnInit {
    // activedNodes: NzTreeNode;
    @ViewChild('nzTree') nzTree: NzTreeComponent;
    @Input() visible = false;
    @Input() title = '';
    @Output() visibleChange = new EventEmitter<boolean>();
    @Output() getTreeNodes = new EventEmitter<any>();
    @Output() manageUserChange = new EventEmitter<void>();

    isOkLoading = false;

    @Input() selectionList: any;
    // selectionList = {
    //     Role: ['Administrator', 'Operator', 'Supervisor']
    // };

    // 1. accessMethod数组
    // 2. 新建一个树节点默认选中的数组

    treeData = RoleTree;
    selectedAccessRight: any[] = [];
    selectedMethodArr: any[] = [];
    selectedUserInfo = null;
    selectedNodeIds = [];
    listOfData = [];
    defaultCheckedKeys = [];
    defaultSelectedKeys = [];
    defaultExpandedKeys = [];
    tree = [];
    submitTree = [];
    isAdd = false;
    editUser = null;
    parenIdList = [];
    pagination = {
        totalEle: 25,
        currentPage: 1,
        currentSize: 10,
        pageSize: 99999
    };

    @Output() manageRoleChange = new EventEmitter<ManageRole>();

    // 初始化表单
    @Input()
    set manageRole(value: ManageRole) {
        if (value) {
            this.selectedMethodArr = value['methodAccess'];
            this.selectedNodeIds = this.selectedMethodArr.reduce((p, c) => [...p, c.accessId], []);
            this.selectedUserInfo = value;
            // const formValue = {
            //     roleName: value.roleName
            // };
            // this.formDataInit(formValue, this.selectedNodeIds);
        }
    }
    userInfoForm: FormGroup;
    constructor(
        private fb: FormBuilder,
        private UMService: UserManagementService,
        private tool: ToolsService,
        private message: NzMessageService,
        private translate: TranslateService
    ) {
        this.userInfoForm = this.fb.group({
            roleName: [null, Validators.required],
            roleDescription: [null, Validators.required]
        });
    }
    private formDataInit(value: ManageRole, selectList) {
        const newParenIdList = this.distinct(this.parenIdList);
        newParenIdList.forEach(element => {
            selectList.forEach((item, idx) => {
                if (element === item) {
                    selectList.splice(idx, 1);
                }
            });
        });
        this.userInfoForm.setValue(value);
        this.defaultCheckedKeys = [];
        this.defaultSelectedKeys = [];
        this.defaultCheckedKeys = [...selectList, 2];
        this.defaultSelectedKeys = [...selectList, 2];
    }

    ngOnInit() {
        //  this.formTreeData();
    }

    close() {
        this.visible = false;
        this.visibleChange.emit(this.visible);
    }
    // 取消
    handleCancel() {
        this.close();
    }
    public getTreeList(id, flag) {
        if (flag === 'add') {
            this.isAdd = true;
            this.editUser = null;
        } else {
            this.isAdd = false;
            this.editUser = id;
        }
        const queryData1 = {
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        const query = this.UMService.getRoleTreeData(queryData1);
        query.subscribe(
            (res: any) => {
                this.listOfData = res.content.content;
                this.formTreeData(res.content.content);
                const formValue = {
                    roleName: id.roleName,
                    roleDescription: id.description
                };
                this.formDataInit(formValue, this.selectedNodeIds);
            },
            (error: any) => {}
        );
    }

    // Role tree 处理
    formTreeData(arr) {
        // tslint:disable-next-line:radix
        this.parenIdList = arr.reduce((p, c) => [...p, parseInt(c.parentId)], []);
        // this.listOfData = arr;
        this.listOfData.forEach((item, idx) => {
            item.key = item.accessId;
            this.translate.get('Layout.Navbar.' + item.rightName).subscribe((res: string) => {
                item.title = res;
            });
            // item.title = item.rightName;
            if (item.parentId === '') {
                item.expanded = true;
            }
            if (!this.parenIdList.includes(item.accessId)) {
                item.isLeaf = true;
            }
        });
        this.tree = [];
        this.tree = this.tool.createTreeData(this.listOfData, 'accessId', 'parentId');
        this.tree[0].children.forEach(item => {
            if (item.rightName === 'Overall') {
                item.disabled = true;
            }
        });
    }
    nzEvent(event: NzFormatEmitEvent): void {}
    distinct(a) {
        return Array.from(new Set([...a]));
    }
    submitForm(): void {
        this.submitTree = [];
        const tempTree = this.nzTree.getCheckedNodeList();
        this.getTreeNode(tempTree, 0);
        for (const i in this.userInfoForm.controls) {
            if (this.userInfoForm.controls.hasOwnProperty(i)) {
                this.userInfoForm.controls[i].markAsDirty();
                this.userInfoForm.controls[i].updateValueAndValidity();
            }
        }
        if (this.userInfoForm.value.roleName === '') {
            // this.message.create('warning', 'Please enter role name.');
            return;
        }
        const accessList = [];
        this.distinct(this.submitTree).forEach(item => {
            const data = {
                accessId: item,
                id: 0,
                userRole_Id: 0
            };
            accessList.push(data);
        });
        let query;
        if (this.isAdd) {
            const userRoleId = 0;
            const queryData = {
                createTime: new Date(),
                description: this.userInfoForm.value.roleDescription,
                methodAccess: accessList,
                roleName: this.userInfoForm.value.roleName,
                updateTime: new Date(),
                userRole_Id: userRoleId
            };
            query = this.UMService.createUserRole(queryData);
        } else {
            const userRoleId = this.editUser.userRole_Id;
            const queryData = {
                createTime: this.selectedUserInfo.createTime,
                description: this.userInfoForm.value.roleDescription,
                methodAccess: accessList,
                roleName: this.userInfoForm.value.roleName,
                updateTime: new Date(),
                userRole_Id: userRoleId
            };
            query = this.UMService.updateUserRole(queryData);
        }
        query.subscribe(
            res => {
                if (res.code === '000000') {
                    this.manageUserChange.emit();
                    this.message.create('success', res.msg);
                } else {
                    this.message.create('warning', res.msg);
                }
            },
            err => {}
        );
    }
    getTreeNode(arr, index) {
        arr.forEach(element => {
            const childs = element._children;
            this.submitTree.push(element.origin.accessId);
            if (element.origin.parentId !== '') {
                this.submitTree.push(parseInt(element.origin.parentId));
                this.tree.forEach(item => {
                    if (item.children) {
                        item.children.forEach(child => {
                            if (child.accessId === element.origin.parentId) {
                                this.submitTree.push(parseInt(child.parentId));
                            }
                        });
                    }
                });
            }
            if (childs && childs.length > 0) {
                this.getTreeNode(childs, index + 1);
            }
        });
    }
    // role tree 处理结束
}
